#region Copyright (c) 2006-2009 Widgetsphere LLC, All Rights Reserved
//--------------------------------------------------------------------- *
//                          Widgetsphere  LLC                           *
//             Copyright (c) 2006-2009 All Rights reserved              *
//                                                                      *
//                                                                      *
//This file and its contents are protected by United States and         *
//International copyright laws.  Unauthorized reproduction and/or       *
//distribution of all or any portion of the code contained herein       *
//is strictly prohibited and will result in severe civil and criminal   *
//penalties.  Any violations of this copyright will be prosecuted       *
//to the fullest extent possible under law.                             *
//                                                                      *
//THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED     *
//TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND         *
//TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
//CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY     *
//THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF WIDGETSPHERE LLC   *
//                                                                      *
//UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN     *
//PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR  *
//SUBSTANTIALLY THE SAME, FUNCTIONALITY AS ANY WIDGETSPHERE PRODUCT.    *
//                                                                      *
//THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE           *
//CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF WIDGETSPHERE,      *
//INC.  THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO       *
//INSURE ITS CONFIDENTIALITY.                                           *
//                                                                      *
//THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT        *
//PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN       *
//EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING         *
//THE PRODUCT.  IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE            *
//SOURCE CODE CONTAINED HEREIN.                                         *
//                                                                      *
//THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.              *
//--------------------------------------------------------------------- *
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Widgetsphere.Generator
{
  public partial class ConnectStringForm : Form
  {
    public ConnectStringForm()
    {
      InitializeComponent();

      this.RefreshEnabled();
      this.LoadSettings();
    }

    private DataImportOptions ImportOptions = new DataImportOptions();

    #region Property Implementations

    public string ConnectString
    {
      get
      {
				return this.ImportOptions.GetConnectionString();
				//if(opt1.Checked)
				//{
				//  return "data source=" + txtServer.Text + ";Initial Catalog=" + txtDatabase.Text + ";uid=" + txtUID.Text + ";pwd=" + txtPWD.Text + ";";
				//}
				//else
				//{
				//  return txtConnectionString.Text;
				//}
      }
    }

    private string FileName
    {
      get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Widgetsphere\Widgetsphere.ConnectionDialog.config.xml"); }
    }

    #endregion

		#region Event Handlers

		private void cmdOK_Click(object sender, System.EventArgs e)
    {
      this.SaveSettings();
      this.DialogResult = DialogResult.OK;
      this.Close();
    }

    private void cmdCancel_Click(object sender, System.EventArgs e)
    {
      this.DialogResult = DialogResult.Cancel;
      this.Close();
    }

    private void opt1_CheckedChanged(object sender, System.EventArgs e)
    {
      if(opt1.Checked)
        opt2.Checked = false;
      this.RefreshEnabled();
    }

    private void opt2_CheckedChanged(object sender, System.EventArgs e)
    {
      if(opt2.Checked)
        opt1.Checked = false;
      this.RefreshEnabled();
    }

		private void chkWinAuth_CheckedChanged(object sender, EventArgs e)
		{
			lblUID.Enabled = !chkWinAuth.Checked;
			txtUID.Enabled = !chkWinAuth.Checked;
			lblPWD.Enabled = !chkWinAuth.Checked;
			txtPWD.Enabled = !chkWinAuth.Checked;
		}

		#endregion

		#region Methods

		private void RefreshEnabled()
    {
      lblServer.Enabled = opt1.Checked;
      lblDatabase.Enabled = opt1.Checked;
      lblUID.Enabled = opt1.Checked;
      lblPWD.Enabled = opt1.Checked;
      txtServer.Enabled = opt1.Checked;
      txtDatabase.Enabled = opt1.Checked;
      txtUID.Enabled = opt1.Checked;
      txtPWD.Enabled = opt1.Checked;

      lblConnectionString.Enabled = opt2.Checked;
      txtConnectionString.Enabled = opt2.Checked;
    }

    private void LoadSettings()
    {
      FileInfo fi = new FileInfo(this.FileName);
      if(!fi.Directory.Exists)
        fi.Directory.Create();

      ImportOptions.LoadXML(this.FileName);

      opt1.Checked = !ImportOptions.UseConnectionString;
      opt2.Checked = ImportOptions.UseConnectionString;
      txtConnectionString.Text = ImportOptions.ConnectionString;
      txtDatabase.Text = ImportOptions.Database;
      txtPWD.Text = ImportOptions.PWD;
      txtServer.Text = ImportOptions.Server;
      txtUID.Text = ImportOptions.UID;
			chkWinAuth.Checked = ImportOptions.UseWinAuth;
      
    }

    private void SaveSettings()
    {
      ImportOptions.UseConnectionString = !opt1.Checked;
      ImportOptions.ConnectionString = txtConnectionString.Text;
      ImportOptions.Database = txtDatabase.Text;
      ImportOptions.PWD = txtPWD.Text;
      ImportOptions.Server = txtServer.Text;
      ImportOptions.UID = txtUID.Text;
			ImportOptions.UseWinAuth = chkWinAuth.Checked;

      ImportOptions.SaveXML(this.FileName);
    }

    #endregion

  }

  public class DataImportOptions
  {

    #region Class Memebers

    protected internal const string MyXMLNodeName = "options";
    private const string startXPath = @"//" + MyXMLNodeName + @"/";

    protected string _connectionString = "";
    protected string _server = "";
    protected string _database = "";
    protected string _uid = "";
    protected string _pwd = "";
    protected bool _useConnectionString = true;
    protected string _cacheFolder = "";
		protected bool _useWinAuth = false;

    #endregion

    #region Property Implementations

    public static string FileName
    {
      get
      {
        string retval = System.Windows.Forms.Application.ExecutablePath;
        retval = new System.IO.DirectoryInfo(retval).Parent.FullName;
        if(!retval.EndsWith(@"\"))
          retval += @"\";
        retval += "options.xml";
        return retval;
      }
    }

    public string ConnectionString
    {
      get { return _connectionString; }
      set { _connectionString = value; }
    }

    public string Server
    {
      get { return _server; }
      set { _server = value; }
    }

    public string Database
    {
      get { return _database; }
      set { _database = value; }
    }

    public string UID
    {
      get { return _uid; }
      set { _uid = value; }
    }

    public string PWD
    {
      get { return _pwd; }
      set { _pwd = value; }
    }

    public bool UseConnectionString
    {
      get { return _useConnectionString; }
      set { _useConnectionString = value; }
    }

    public string CacheFolder
    {
      get { return _cacheFolder; }
      set { _cacheFolder = value; }
    }

		public bool UseWinAuth
		{
			get { return _useWinAuth; }
			set { _useWinAuth = value; }
		}

    #endregion

    #region Methods

    public string GetConnectionString()
    {
      if(this.UseConnectionString)
        return this.ConnectionString;
      else if (this.UseWinAuth)
				return "data source=" + this.Server + ";database=" + this.Database + ";Integrated Security=SSPI;Persist Security Info=False;";
			else
				return "data source=" + this.Server + ";database=" + this.Database + ";uid=" + this.UID + ";pwd=" + this.PWD + ";";
    }

    #endregion

    #region IXMLable Members

    public string ToXML()
    {
      return this.XmlNode().OuterXml;
    }

    public bool FromXML(string xml)
    {
      System.Xml.XmlDocument document = new System.Xml.XmlDocument();
      try
      {
        //Setup the Node Name
        document.InnerXml = xml;

        //Load all properties
        _connectionString = Widgetsphere.Generator.Common.Util.XmlHelper.GetNodeValue(document, startXPath + "connectionstring", this.ConnectionString);
        _server = Widgetsphere.Generator.Common.Util.XmlHelper.GetNodeValue(document, startXPath + "server", this.Server);
        _database = Widgetsphere.Generator.Common.Util.XmlHelper.GetNodeValue(document, startXPath + "database", this.Database);
        _uid = Widgetsphere.Generator.Common.Util.XmlHelper.GetNodeValue(document, startXPath + "uid", this.UID);
        _pwd = Widgetsphere.Generator.Common.Util.XmlHelper.GetNodeValue(document, startXPath + "pwd", this.PWD);
        _useConnectionString = bool.Parse(Widgetsphere.Generator.Common.Util.XmlHelper.GetNodeValue(document, startXPath + "useconnectionstring", this.UseConnectionString.ToString()));
        _cacheFolder = Widgetsphere.Generator.Common.Util.XmlHelper.GetNodeValue(document, startXPath + "cachefolder", this.CacheFolder);
				_useWinAuth = bool.Parse(Widgetsphere.Generator.Common.Util.XmlHelper.GetNodeValue(document, startXPath + "usewinauth", this.UseWinAuth.ToString()));

        return true;
      }
      catch(Exception ex)
      {
        throw;
      }

    }

    public bool SaveXML(string fileName)
    {
      System.Xml.XmlDocument document = new System.Xml.XmlDocument();
      document.LoadXml(this.ToXML());
      document.Save(fileName);
      return true;
    }

    public bool LoadXML(string fileName)
    {
      if(System.IO.File.Exists(fileName))
      {
        System.Xml.XmlDocument document = new System.Xml.XmlDocument();
        document.Load(fileName);
        this.FromXML(document.DocumentElement.OuterXml);
        return true;
      }
      return false;
    }

    internal virtual System.Xml.XmlNode XmlNode()
    {
      System.Xml.XmlDocument document = new System.Xml.XmlDocument();
      System.Xml.XmlElement parentNode = null;

      try
      {
        //Setup the Node Name
        parentNode = (System.Xml.XmlElement)Widgetsphere.Generator.Common.Util.XmlHelper.AddElement(document, MyXMLNodeName, "");

        //Add the appropriate properties
        Widgetsphere.Generator.Common.Util.XmlHelper.AddElement(parentNode, "connectionstring", this.ConnectionString);
        Widgetsphere.Generator.Common.Util.XmlHelper.AddElement(parentNode, "server", this.Server);
        Widgetsphere.Generator.Common.Util.XmlHelper.AddElement(parentNode, "database", this.Database);
        Widgetsphere.Generator.Common.Util.XmlHelper.AddElement(parentNode, "uid", this.UID);
        Widgetsphere.Generator.Common.Util.XmlHelper.AddElement(parentNode, "pwd", this.PWD);
        Widgetsphere.Generator.Common.Util.XmlHelper.AddElement(parentNode, "useconnectionstring", this.UseConnectionString.ToString());
        Widgetsphere.Generator.Common.Util.XmlHelper.AddElement(parentNode, "cachefolder", this.CacheFolder);
				Widgetsphere.Generator.Common.Util.XmlHelper.AddElement(parentNode, "usewinauth", this.UseWinAuth.ToString());

        return parentNode;

      }
      catch(Exception ex)
      {
        throw;
      }
    }
    #endregion
  }

}